import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/record/channel_logic.dart';
import 'package:sports_new/server/api/record_api.dart';
import 'package:sports_new/utils/utils.dart';

import '../../entity/record/football/zq_points_entity.dart';
import '../../entity/record/points_entity.dart';

class PointsLogic extends GetxController{
  final String? seasonTag;
  final int? leagueId;
  PointsLogic(this.leagueId, {this.seasonTag});
  
  late final channel = Get.find<ChannelLogic>(tag: seasonTag);
  PointsEntity? entity;
  List<PointsList>? pointsData;
  List<MatchStage>? matches;
  int qualifyIndex = 0;
  bool _visible = false;
  bool isLoading = true;
  EasyRefreshController refreshController = EasyRefreshController();

  bool get visible => _visible;

  set visible(bool value) {
    _visible = value;
    update();
  }

  @override
  void onInit() async{
    await getData();
    var currentSeason = channel.season;
    channel.addListener(() {
      if(currentSeason != channel.season){
        getData();
        currentSeason = channel.season;
      }
    });
    super.onInit();
  }

  Future getData() async{
    entity = await RecordApi.getPoints(
      leagueId: leagueId ?? 0,
      season: channel.season,
      seasonId: channel.seasonId,
      recordType: channel.recordType
    );
    matches = entity?.matchStages;
    isLoading = false;
    update();
  }

  String introduce(data){
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    String append = '';
    data.split("").forEach((element) {
      if(regC.hasMatch(element)){
        append += "$element\u200A";
      }else{
        append += element;
      }
    });
    return append;
  }

  List qualification(List<RankingQualify> list){
    for(var i = 0;i < list.length; i++){
      for(var j = i+1;j<list.length;j++){
        if(list[i].beginRank == list[j].beginRank){
          list.removeAt(i);
        }
      }
    }
    return list;
  }


  void doRefresh() {
    if(refreshController.headerState?.mode.isIdle == false) return;
    refreshController.callRefresh();
  }

  @override
  void dispose() {
    channel.removeListener(() {});
    super.dispose();
  }
}